package com.seezoon.domain.service.device;

import com.seezoon.domain.dao.mapper.DeviceInfoMapper;
import com.seezoon.domain.dao.mapper.UserDeviceMapper;
import com.seezoon.domain.dao.po.DeviceInfoPO;
import com.seezoon.domain.dao.po.UserDevicePO;
import com.seezoon.infrastructure.error.ErrorCode;
import com.seezoon.infrastructure.exception.ExceptionFactory;
import jakarta.validation.constraints.NotNull;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

@Slf4j
@RequiredArgsConstructor
@Service
@Validated
public class DeviceService {

    private final DeviceInfoMapper deviceInfoMapper;
    private final UserDeviceMapper userDeviceMapper;

    /**
     * 发送设备消息前检查
     *
     * @param uid
     * @param deviceId
     * @return not null
     */
    @Transactional
    public DeviceInfoPO sendDeviceMsgCheck(@NotNull Long uid, @NotNull Long deviceId) {
        DeviceInfoPO deviceInfoPO = deviceInfoMapper.selectByPrimaryKey(deviceId);
        if (deviceInfoPO == null) {
            throw ExceptionFactory.bizException(ErrorCode.DEVICE_NOT_EXISTS);
        }

        if (!Objects.equals(deviceInfoPO.getDeviceStatus(), DeviceInfoPO.ONLINE)) {
            throw ExceptionFactory.bizException(ErrorCode.DEVICE_NOT_ONLINE);
        }
        UserDevicePO userDevicePO = userDeviceMapper.selectByUidAndDeviceId(uid, deviceInfoPO.getId());
        if (userDevicePO == null) {
            throw ExceptionFactory.bizException(ErrorCode.DEVICE_NOT_BIND);
        }
        return deviceInfoPO;
    }
}
